﻿using System;
using System.Linq;
using System.Xml;
using Google.Protobuf.WellKnownTypes;
using HamcoWcs.Tools.Tibco.Entities;
using TIBCO.Rendezvous;

namespace HamcoWcs.Tools.Tibco
{
    public partial class TibcoTool
    {
        private void LogAll(string msg)
        {
            var messageName = XmlHelper.GetMessageName(msg);
            var timeStamp = XmlHelper.GetTransactionId(msg);
            var mesMsgQueue = new MesMsgQueueBak()
            {
                Id = 0,
                Sender = EnumMesMsgSender.MES,
                Content = msg,
                EventName = messageName,
                Status = EnumMesMsgStatus.MesRequest,
                Return = "",
                BusinessType = "",
                RequestType = EnumMesRequestType.Request,
                CreatedTime = DateTime.Now,
                LastUpdateTime = DateTime.Now,
                TransactionId = timeStamp
            };

            int count = _context.Client.Insertable(mesMsgQueue).ExecuteCommand();
            if (count < 1)
            {
                var systemlog = new SystemErrorLog($"TibcoExchange Server:[ERROR]{timeStamp},{messageName}");
                _context.Client.Insertable(systemlog).ExecuteCommand();
            }
        }

        /// <summary>接收MES数据处理</summary>
        private void ReceiveHandler(object listener, MessageReceivedEventArgs messageReceivedEventArgs)
        {
            string message = messageReceivedEventArgs.Message.GetField(_config.SendField).Value.ToString() ?? "";
            OnReceiving?.Invoke(message);
            var messageName = XmlHelper.GetMessageName(message).ToUpper();
            if (string.IsNullOrEmpty(messageName)) return;


            try
            {
                LogAll(message);
            }
            catch (Exception)
            {

            }

            if (messageName.Contains("REPLY"))
                HandleReceiveReply(message);


            if (messageName.Equals("CurrentDateTime",StringComparison.OrdinalIgnoreCase)
             || messageName.Equals("MachineStateReportByMES", StringComparison.OrdinalIgnoreCase)
             )
                HandleMesReport(message);

            if (messageName.Contains("REQUEST"))
            {
                HandleReceiveRequest(message);

                // 开启虚拟Tibco服务（测试SPEC用）
                //if (_config.IsBuildWithVirtualTibcoServer)
                //    VirtualTibcoServer.DoVirtualReply(messageName, message, SendVirtualReply);
                ////}
            }

        }

        private void HandleMesReport(string msg)
        {
            HandleReceiveRequest(msg);
        }

        private void HandleReceiveRequest(string msg)
        {
            var messageName = XmlHelper.GetMessageName(msg);
            var timeStamp = XmlHelper.GetTransactionId(msg);

            if (messageName.Diff("AreYouThereRequest")) return;
            if (messageName.Diff("MachineModeChangeRequest")) return;
            if (messageName.Diff("ChangeMachinePalletTypeRequest")) return;
            if (messageName.Diff("PalletAndBoxAssignRequest")) return;
            if (messageName.Diff("ValidatePalletListRequest")) return;
            if (messageName.Diff("ValidatePalletInputRequest")) return;
            if (messageName.Diff("InventoryPalletDataRequest")) return;
            if (messageName.Diff("INVENTORYZONEDATAREQUEST")) return;



            
            var oldMsg = _context.Client.Queryable<MesMsgQueue>().First(x => x.TransactionId == timeStamp);




            if (oldMsg != null)
            {
                if (messageName.Equals("PalletRequestTransportJobRequest"))
                {
                    var a= XmlHelper.SetJobReply(msg);
                    a = XmlHelper.SetNGReturn(a,"90","Already has the same transactionid message,please resend.");
                    Send(a,_context.SendSubject);

                    var systemlog = new SystemErrorLog($"TibcoExchange Server:[ERROR]{timeStamp},Already has the same transactionid message,please resend.");
                    _context.Client.Insertable(systemlog).ExecuteCommand();
                }


                return;
            }

            var mesMsgQueue = new MesMsgQueue()
            {
                Id = 0,
                Sender = EnumMesMsgSender.MES,
                Content = msg,
                EventName = messageName,
                Status = EnumMesMsgStatus.MesRequest,
                Return = "",
                BusinessType = "",
                RequestType = EnumMesRequestType.Request,
                CreatedTime = DateTime.Now,
                LastUpdateTime = DateTime.Now,
                TransactionId = timeStamp
            };

            int count = _context.Client.Insertable(mesMsgQueue).ExecuteCommand();
            if (count < 1)
            {
                var systemlog = new SystemErrorLog($"TibcoExchange Server:[ERROR]{timeStamp},{messageName}");
                _context.Client.Insertable(systemlog).ExecuteCommand();
            }
        }

        private MesMsgQueue GetMsgByTimeStamp(string xml)
        {
            string timeStamp = XmlHelper.GetTransactionId(xml);
            var msgs = _context.Client
                               .Queryable<MesMsgQueue>()
                               .Where(d => d.TransactionId == timeStamp)
                               .ToList();

            if (msgs == null || msgs.Count == 0) return null;

            return msgs.First();
        }

        private void HandleReceiveReply(string xml)
        {
            string timeStamp = XmlHelper.GetTransactionId(xml);

            if (timeStamp[0] == 'R') timeStamp = timeStamp.Substring(1);

            var sql = _context.Client.Queryable<MesMsgQueue>().ToSql();
            var mm = _context.Client.Queryable<MesMsgQueue>().ToList();

            var msgs = _context.Client
                               .Queryable<MesMsgQueue>()
                               .Where(d => d.TransactionId == timeStamp)
                               .Where(d => d.Status == EnumMesMsgStatus.WcsWaitRecv)
                               .ToList();

            if (msgs == null || msgs.Count == 0) return;

            var msg = msgs.First();
            msg.Return = xml;
            msg.Status = EnumMesMsgStatus.WcsReceived;
            _context.Client.Updateable(msg).ExecuteCommand();
        }
    }
}
